import React, { useEffect, useState } from 'react'
import BraftEditor, { EditorState } from 'braft-editor'
import 'braft-editor/dist/index.css'
import { uploadFile } from '@/utils/request'
interface IProps {
  value?: any
  onChange?: () => void
  readOnly?: boolean
}
export default function BraftEditorWithUpload(props: IProps) {
  useEffect(() => {
    if (props.value) {
      setEditorState(BraftEditor.createEditorState(props.value))
    }
  }, [props.value])
  const [editorState, setEditorState] = useState<EditorState>(BraftEditor.createEditorState(null))
  // 定义rem基准值
  const sizeBase = 23.4375
  // 定义输入转换函数
  const unitImportFn = (unit: any, type: any, source: any) => {
    // type为单位类型，例如font-size等
    // source为输入来源，可能值为create或paste
    // 此函数的返回结果，需要过滤掉单位，只返回数值
    if (unit.indexOf('rem')) {
      return parseFloat(unit) * sizeBase
    } else {
      return parseFloat(unit)
    }
  }

  // 定义输出转换函数
  const unitExportFn = (unit: any, type: any, target: any) => {
    if (type === 'line-height') {
      // 输出行高时不添加单位
      return unit
    }

    // target的值可能是html或者editor，对应输出到html和在编辑器中显示这两个场景
    if (target === 'html') {
      // 只在将内容输出为html时才进行转换
      return unit / sizeBase + 'rem'
    } else {
      // 在编辑器中显示时，按px单位展示
      return unit + 'px'
    }
  }
  // 图片上传处理
  const handleFileUpload = async (param: any) => {
    const formData = new FormData()
    formData.append('file', param.file)
    try {
      const response = await uploadFile(param.file)
      const { linkUrl } = response.data
      param.success({ url: linkUrl })
    } catch (error) {
      param.error({ msg: '上传失败，请重试' })
    }
  }

  const handleEditorChange = (state: EditorState) => {
    console.log(state.toHTML())
    setEditorState(state)
  }

  return (
    <div>
      <BraftEditor
        value={editorState}
        onChange={handleEditorChange}
        media={{ uploadFn: handleFileUpload }}
        // converts={{ unitImportFn, unitExportFn }}
        readOnly={props.readOnly}
        controls={props.readOnly ? [] : undefined} // 控制面板
      />
    </div>
  )
}
